package com.senven.common.pojo.controller;

import com.alibaba.fastjson.JSON;

import com.senven.common.entity.Address;
import com.senven.common.entity.User;
import com.senven.common.pojo.feign.AddressFeign;
import com.senven.common.pojo.feign.UserFeign;
import com.senven.common.pojo.vo.CommonResult;
import com.senven.common.pojo.vo.LoginVo;
import com.senven.common.pojo.feign.PermissionFeign;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: senven-orderfood-parent
 * @BelongsPackage: com.senven.controller
 * @unthor : YSH
 * @date : 2022/8/29 19:44
 */
@RestController
@RequestMapping("/sso")
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private PermissionFeign permissionFeign;
    @Autowired
    private AddressFeign addressFeign;



    //后台登录
    @Autowired
    private UserFeign userFeign;
    //后台登录
    @PostMapping("/login")
    public CommonResult login(@RequestBody LoginVo loginVo){
        Integer roleid = userFeign.yonghuLogin(loginVo.getUsername());
        if(roleid<3) {
            Subject subject = SecurityUtils.getSubject();
            try {
                UsernamePasswordToken token = new UsernamePasswordToken(loginVo.getUsername(), loginVo.getPassword());
                //交于shiro自定义realm中的认证方法
                subject.login(token);

                //生成token. (1)UUID生成一个唯一id并把该值保存到redis中 [2]通过JWT来生成token.[(1)头信息 (2)载体 (3)密钥]
                String uuid = UUID.randomUUID().toString().replace("-", "");
                //登录成功后的用户信息
                User user = (User) subject.getPrincipal();
                user.setPassword(null);
                //根据用户id查询该用户具有的权限。
                List<String> permissions = permissionFeign.findPermissionByUserid(user.getId());
                //getData():LinkedHashMap
                Map<String, Object> map = new HashMap<>();
                map.put("user", user);
                map.put("permissions", permissions);
                System.out.println(map+"=====================");
                // 保存在redis中 value应该为包含用户信息以及该用户具有的权限
                redisTemplate.opsForValue().set(uuid, JSON.toJSONString(map), 24, TimeUnit.HOURS);
                return new CommonResult(2000, "登录成功", uuid);
            } catch (Exception e) {
                e.printStackTrace();
                return new CommonResult(5000, "账号或密码错误", null);
            }
        }else{
            return new CommonResult(5001,"权限不足",null);
        }
    }

    //App端登录
    @PostMapping("/denglu")
    public CommonResult ALogin(@RequestBody LoginVo loginVo){
        Integer roleid = userFeign.yonghuLogin(loginVo.getUsername());
        if(roleid>2) {
            Subject subject = SecurityUtils.getSubject();
            try {
                UsernamePasswordToken token = new UsernamePasswordToken(loginVo.getUsername(), loginVo.getPassword());
                //交于shiro自定义realm中的认证方法
                subject.login(token);

                //生成token. (1)UUID生成一个唯一id并把该值保存到redis中 [2]通过JWT来生成token.[(1)头信息 (2)载体 (3)密钥]
                String uuid = UUID.randomUUID().toString().replace("-", "");
                //登录成功后的用户信息
                User user = (User) subject.getPrincipal();
                user.setPassword(null);
                String id = user.getId();
                Map<String, String> map1 = new HashMap();
                map1.put("userid", id);
                map1.put("uuid", uuid);

                //根据用户id查询该用户具有的地址

                List<Address> address = addressFeign.findAllAddressByUserId(user.getId());

                //getData():LinkedHashMap
                Map<String, Object> map = new HashMap<>();
                map.put("user", user);
                map.put("address", address);
                System.out.println(map + "==============");


                redisTemplate.opsForValue().set(uuid, JSON.toJSONString(map), 24, TimeUnit.HOURS);
                return new CommonResult(2000, "登录成功", map1);
            } catch (Exception e) {
                e.printStackTrace();
                return new CommonResult(5000, "账号或密码错误", null);
            }
        }else{
            return new CommonResult(5001,"权限不足",null);
        }
    }


    //后台退出
    @PostMapping(value = "/logout")
    public CommonResult logout(HttpServletRequest request){
        String token = request.getHeader("token");
        if(redisTemplate.hasKey(token)){
            Boolean delete = redisTemplate.delete(token);
            return new CommonResult(2000,"退出成功",delete);
        }
        return new CommonResult(5000,"没有找到token",null);
    }
}
